package com.dm.wallpaper.library.helpers;


import com.dm.wallpaper.library.items.Wallpaper;
import com.dm.wallpaper.library.preferences.Preferences;
import ohos.app.Context;
import ohos.app.Environment;

import java.io.File;
import java.text.DecimalFormat;
import java.text.NumberFormat;
/*
 * Wallpaper Board
 *
 * Copyright (c) 2017 Dani Mahardhika
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

public class WallpaperHelper {

    public static final int MB = 1038336;
    public static final int KB = 1024;

    public static File getDefaultWallpapersDirectory(Context context) {
        try {
            if (Preferences.get().getWallsDirectory().length() == 0) {
                return context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
            }
            return new File(Preferences.get().getWallsDirectory());
        } catch (Exception e) {
            return new File(context.getFilesDir(), Environment.DIRECTORY_PICTURES);
        }
    }

    public static String getSize(int size) {
        NumberFormat formatter = new DecimalFormat("#0.00");
        if (size > 1024) {
            double formattedSize = (double) size / WallpaperHelper.MB;
            return formatter.format(formattedSize) + " MB";
        }

        double formattedSize = (double) size / WallpaperHelper.KB;
        return formatter.format(formattedSize) + " KB";
    }

    public static String getFormat(String mimeType) {
        if (mimeType == null) return "jpg";
        switch (mimeType) {
            case "image/jpeg":
                return "jpg";
            case "image/png":
                return "png";
            default:
                return "jpg";
        }
    }

    public static boolean isWallpaperSaved(Context context, Wallpaper wallpaper) {
        String fileName = wallpaper.getName() + "." + getFormat(wallpaper.getMimeType());
        File directory = WallpaperHelper.getDefaultWallpapersDirectory(context);
        File target = new File(directory, fileName);

        if (target.exists()) {
            long size = target.length();
            return size == wallpaper.getSize();
        }
        return false;
    }


}
